package com.test22_日期时间;

import org.junit.Test;

import java.util.Calendar;

/**
 * Calendar，日历类
 */
public class Demo02_Calendar {

    @Test
    public void test1() {
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        System.out.println(String.format("当前的日期时间：%s-%s-%s %s:%s:%s",
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) + 1,       // 月份从0开始
                calendar.get(Calendar.DAY_OF_MONTH),    // 等价于Calendar.DATE
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                calendar.get(Calendar.SECOND)
        ));
    }

    /**
     * 实现日期的准确计算
     */
    @Test
    public void test2() {
        Calendar calendar = Calendar.getInstance();  // 获取对象实例
        calendar.add(Calendar.YEAR, 30);    // 30年之后
        calendar.add(Calendar.MONTH, 6);    // 6个月之后
        System.out.println(String.format("日期时间：%s-%s-%s %s:%s:%s",
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) + 1,
                calendar.get(Calendar.DAY_OF_MONTH),
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                calendar.get(Calendar.SECOND)
        ));
    }

    /**
     * 找到8月的最后一天
     */
    @Test
    public void test3() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), 8, 1);    // 9月份的第一天
        calendar.add(Calendar.DAY_OF_MONTH, -1);    // 9月份的第一天减一
        System.out.println(String.format("当前的日期时间格式：%s-%s-%s %s:%s:%s",
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) + 1,
                calendar.get(Calendar.DAY_OF_MONTH),
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                calendar.get(Calendar.SECOND)
        ));
    }
}
